package com.zt.bigdata.vertx

import com.typesafe.scalalogging.LazyLogging
import com.zt.bigdata.vertx.config.{Config, Container}
import com.zt.bigdata.vertx.controller.ControllerFactory
import io.vertx.core.http.{HttpServer, HttpServerOptions, HttpServerRequest}
import io.vertx.core.{AsyncResult, Handler, Vertx, VertxOptions}
import io.vertx.redis.{RedisClient, RedisOptions}
import javax.annotation.PostConstruct
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

/**
  *
  */
@Component
class Initiator @Autowired()(config: Config, controllerFactory: ControllerFactory) extends LazyLogging {


  @PostConstruct
  def deploy(): Unit = {
    logger.info("Init Vertx...")
    val vertx = Vertx.vertx(new VertxOptions()
      .setEventLoopPoolSize(config.getVertx.eventLoopPoolSize)
      .setWorkerPoolSize(config.getVertx.workerPoolSize)
      .setInternalBlockingPoolSize(config.getVertx.internalBlockingPoolSize)
      .setMaxWorkerExecuteTime(config.getVertx.maxWorkerExecuteTime)
      .setWarningExceptionTime(config.getVertx.warningExceptionTime)
      .setFileResolverCachingEnabled(false)
    )

    vertx.createHttpServer(new HttpServerOptions().setTcpKeepAlive(true))
      .requestHandler(new Handler[HttpServerRequest] {
        override def handle(e: HttpServerRequest): Unit = controllerFactory.initRouter(vertx).accept(e)
      })
      .listen(config.getHttp.port,
        new Handler[AsyncResult[HttpServer]]() {
          override def handle(event: AsyncResult[HttpServer]): Unit = {
            if (event.succeeded()) {
              logger.info("Vertx Http Server Started, port :" + config.getHttp.port)
            } else {
              logger.error("Vertx Http Server Start Fail", event.cause())
            }
          }
        });
    for (i <- 0 to 15) {
      val options = new RedisOptions()
      options.setHost(config.getRedis.host)
        .setPort(config.getRedis.port)
        .setAuth(config.getRedis.auth)
        .setSelect(i)
        .setUsePooledBuffers(true)
      Container.addRedisClient(i, RedisClient.create(vertx, options))
    }

    Container.setResponseContent(new ResponseContent())
    Container.setVertx(vertx)
    logger.info("Vertx Redis Server Start at {}:{}" + config.redis.host, config.redis.host)

  }
}
